"""
@author: Shizuku
@file: 2022-12-07-practice.py
@time: 2022/12/7 15:39
"""


class SinglrNode(object):
    # 单个节点
    def __init__(self, item):
        # 表元素
        self.item = item
        # 指向下一节的链接
        self.next = None


class LinkedList(object):
    def __init__(self):
        # 初始表头部指向None
        self.head = None

    def add(self, item):
        node = SinglrNode(item)
        node.next = self.head
        self.head = node

    def traverse(self):
        cur = self.head
        while cur is not None:
            print(cur.item, end='')
            cur = cur.next
        print('')


def insertreverse(head):
    # 特殊情况：头节点为空，或者只有单个节点
    if head is None or head.next is None:
        return
    # 操作头节点, 2次指针操作,头节点head.next赋值给cur, 由于头节点最终要成为尾结点,其指向为空
    cur = head.next
    head.next = None
    # 操作第二个及之后的节点,每次遍历到的节点都放到头节点处
    while cur:
        nex = cur.next
        cur.next = head
        head = cur
        cur = nex
    return head


link = LinkedList()
print("=========== before =============")
link.add(1)
link.add(2)
link.add(3)
link.add(4)
link.traverse()
print("=========== after ==============")
new_head = insertreverse(link.head)
while new_head:
    print(new_head.item, end='')
    new_head = new_head.next
